package juc.mysynchronized;

/**
 * @ClassName CyclicBarrierExample
 * @PackageName juc.mysynchronized
 * @projectName myThread
 * @Description TODO
 * @Author games
 * @Date 2025/9/4 下午4:08
 * @Version 1.0
 */
import java.util.concurrent.CyclicBarrier;

/**
 * 1. CyclicBarrier（回环栅栏或循环屏障）
 * 应用场景：
 *
 * 人满发车，批量数据处理：当一组线程到达某个状态（屏障点）之后再全部同时执行，并且可以被重复使用。
 * 多级任务分配：将复杂的任务分配给多个线程执行，并在所有线程完成工作后触发后续操作。
 * 数据处理：协调多个线程间的数据处理，在所有线程处理完数据后触发后续操作。
 *
 */
public class CyclicBarrierExample {
    private static final int THREAD_COUNT = 5;
    private static final CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT, () -> {
        System.out.println("All threads have reached the barrier point.");
    });

    public static void main(String[] args) {
        for (int i = 0; i < THREAD_COUNT; i++) {
            new Thread(() -> {
                try {
                    System.out.println(Thread.currentThread().getName() + " is working.");
                    Thread.sleep((long) (Math.random() * 1000));
                    System.out.println(Thread.currentThread().getName() + " has finished its work.");
                    barrier.await(); // 等待其他线程到达屏障点
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        }

        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                try {
                    System.out.println(Thread.currentThread().getName() + " is working.");
                    Thread.sleep((long) (Math.random() * 1000));
                    System.out.println(Thread.currentThread().getName() + " has finished its work.");
                    barrier.await(); // 等待其他线程到达屏障点
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
        }

    }
}